package main.leetcode.offer.secondround.from03to50;

import main.datastruc.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/** 32-I.从上到下打印二叉树 */
public class ex31I {
    public static void main(String[] args) {
        TreeNode root = TreeNode.creCmpBTree(new int[] {3, 9, 20, 1, 1, 15, 7});
        System.out.println(Arrays.toString(new ex31I().levelOrder(root)));
    }

    public int[] levelOrder(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        levelOrder(root, list);
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); ++i) {
            res[i] = list.get(i);
        }
        return res;
    }

    private void levelOrder(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.add(root);
        TreeNode node;
        while (!stack.isEmpty()) {
            node = stack.poll();
            list.add(node.val);
            if (node.left != null) {
                stack.add(node.left);
            }
            if (node.right != null) {
                stack.add(node.right);
            }
        }
    }
}
